/**
 * @fileoverview Giant Interective Group, Inc. Javascript Library v#version.
 * 该Javascript UI库是基于jQuery的扩展。
 * <pre>
 * Copyright (C) 2004-2009 Giant Interective Group, Inc. All rights reserved.
 * 版权所有 2004-2009 上海巨人网络科技有限公司
 * </pre>
 * 
 * @version #version, #date
 * @author  Songlu
 */

if(typeof giant === 'undefined')
    var giant = {};

if(typeof giant.ui === 'undefined')
	giant.ui = {};

(function($) {
	
	giant.ui.MainTabs = function(configs){
		this.initMainTabs(configs);	
	};

	giant.ui.MainTabs.prototype = {
		
		initMainTabs: function(configs){
			var options = {
				//最大历史记录，指用户自定义选项卡的最大数
				maxHistoryCount: 20,
				perCookieSaveCount: 5,
				//用户自定义选项卡显示的个数
				showUserTabsCount: 5,
				mainCtn: '#container',
				tabCtn: '#tabs',
				userTabCtn: '#subTabs',
				btnLeft: '#btnLeft',
				btnRight: '#btnRight',
				btnDropDown: '#btnDropDown',
				dropDownListCtn: '#dropDownListCtn',
				userTabWidth: 112
			}
			
			$.extend(options, configs||{});
			//初始化
			$this = this;
			
			//主容器
			this.elmMainCtn = $(options.mainCtn);
			//选项卡容器
			this.elmTabCtn = $(options.tabCtn);
			//用户选项卡容器
			this.elmUserTabCtn = $(options.userTabCtn);
			//向左移动按钮
			this.btnMoveLeft = $(options.btnLeft);
			//向右移动按钮
			this.btnMoveRight = $(options.btnRight);
			//下拉列表按钮
			this.btnDropDown = $(options.btnDropDown);
			//下拉列表容器
			this.elmDropDownListCtn = $(options.dropDownListCtn);
			
			this.iUserTabWidth = options.userTabWidth;
			this.iShowUserTabCount = options.showUserTabsCount;
			this.iMaxHistoryCount = options.maxHistoryCount;
			this.iPerCookieSaveCount = options.perCookieSaveCount;
			this.lUid = options.uid;
			this.sUname = options.uname;
			this.lTokenId = options.tokenId;
			//存储选项卡，包含系统选项卡和用户选项卡
			this.aTabs = [];
			this.timer = null;
			this.offer = 0;
			this.start = 0;
			
			
			//添加系统默认选项卡
			$.each($this.elmTabCtn.children('li.ui-systemtab'),function(index, itm){
				var oTab = {};
				oTab.tab = itm;
				oTab.tabCont = $(itm).children('a');
				oTab.tabUrl = oTab.tabCont.attr('href');
				oTab.tabId = $this.lTokenId;
				oTab.tabName = oTab.tabCont.html();
				$this.aTabs.push(oTab);
				oTab.tabCont.bind('click', function(event){
					$this.setCookie('currentIndex', index);
				})
				
				var oElmListItm = $('<li></li>');
				var oElmListItmCont = $('<a href="javascript:void(0);"></a>');
				oElmListItmCont.attr('href',oTab.tabUrl);
				oElmListItmCont.html(oTab.tabName);
				oElmListItmCont.bind('click', function(event){
					$this.setCookie('currentIndex', index);
				})
				oElmListItm.append(oElmListItmCont);
				oTab.listItm = oElmListItm;
				oTab.listItmCont = oElmListItmCont; 
				$this.elmDropDownListCtn.append(oElmListItm);
			})
			
			this.iSystemTabCount = this.aTabs.length;
			
			//读取cookie，加载用户选项卡
//			alert(document.cookie);
			//获取访问历史数组
			var aHistory = this.getHistoryArray();
			for(var i=0; i<aHistory.length; i++){
				this.addTab({'tabName':aHistory[i].split('|')[0], 'tabUrl':aHistory[i].split('|')[1], 'tabId': aHistory[i].split('|')[2]});
			}
			this.iCurrentIndex = (this.getCookie('currentIndex') == '')?options.currentIndex:this.getCookie('currentIndex');
			this.iCurrentIndex = this.iCurrentIndex || 0;
			if(this.lUid != this.lTokenId){
				//访问的是用户朋友的相关页面，或者陌生人页面
				if(this.isExist(this.lUid)==-1){
					this.addTab({'tabName':this.sUname, 'tabUrl': location.href, 'tabId': this.lUid});
					this.iCurrentIndex = this.aTabs.length - 1;
					this.addHistory(this.sUname, location.href, this.lUid);
				}else{
					this.iCurrentIndex = this.isExist(this.lUid);
					this.updateHistory(this.sUname, location.href, this.lUid, this.iCurrentIndex - this.iSystemTabCount);
				}
			}			
			$(document).bind('click', function(event){
				if(event.target.className == 'add'){
					$this.elmDropDownListCtn.toggle();
				}else{
					$this.elmDropDownListCtn.hide();
				}
			})
			
			//阻断a标签默认事件。
			this.btnMoveLeft.bind('mousedown', function(event){
				if($this.timer != null){
					return;
				}
				
				$this.start = parseInt($this.elmUserTabCtn.css('margin-left'));
				if($this.start == 0){
					return;
				}
				$this.timer = window.setInterval(function(){
					$this.elmUserTabCtn.css('margin-left',parseInt($this.start + $this.offer)+'px');
					$this.offer+=5;
					
					if($this.offer > $this.iUserTabWidth){
						$this.elmUserTabCtn.css('margin-left',parseInt($this.start + $this.iUserTabWidth)+'px');
						$this.setCookie('marginLeft',parseInt($this.start + $this.iUserTabWidth)+'px');
						if($this.start+$this.iUserTabWidth == 0){
							$this.btnMoveLeft.addClass('offleft');
							$this.btnMoveRight.removeClass('offright');
						}else{
							$this.btnMoveLeft.removeClass('offleft');
							$this.btnMoveRight.removeClass('offright');
						}
						clearInterval($this.timer);
						$this.timer = null;
						$this.offer = 0;
						$this.start = 0;
					}
					
				},10);				
			});
			
			this.btnMoveRight.bind('mousedown', function(event){
				if($this.timer != null){
					return;
				}
				
				$this.start = parseInt($this.elmUserTabCtn.css('margin-left'));
				if(-$this.start + $this.elmUserTabCtn.parent().width() >= ($this.aTabs.length-$this.iSystemTabCount) * $this.iUserTabWidth){
					$(this).addClass('offright');
					return;
				}
				$this.timer = window.setInterval(function(){
					$this.elmUserTabCtn.css('margin-left',parseInt($this.start - $this.offer)+'px');
					$this.offer+=5;
					
					if($this.offer > $this.iUserTabWidth){
						$this.elmUserTabCtn.css('margin-left',parseInt($this.start - $this.iUserTabWidth)+'px');
						$this.setCookie('marginLeft',parseInt($this.start - $this.iUserTabWidth)+'px');
						if($this.start-$this.iUserTabWidth == -($this.aTabs.length-$this.iSystemTabCount-$this.iShowUserTabCount)*$this.iUserTabWidth){
							$this.btnMoveRight.addClass('offright');
							$this.btnMoveLeft.removeClass('offleft');
						}else{
							$this.btnMoveRight.removeClass('offright');
							$this.btnMoveLeft.removeClass('offleft');
						}
						clearInterval($this.timer);
						$this.timer = null;
						$this.offer = 0;
						$this.start = 0;
					}
					
				},10);				
			});
			this.elmUserTabCtn.css('margin-left',($this.getCookie('marginLeft')=='')?'0px':$this.getCookie('marginLeft'));
			this.showTab(this.iCurrentIndex);
			
		},
		getHistoryArray: function(){
			var aHistory = [];
			for(var i=0; i<this.iMaxHistoryCount/this.iPerCookieSaveCount; i++){
				if(this.getCookie('giant_history_'+i) != ''){
					aHistory = aHistory.concat(this.getCookie('giant_history_'+i).split('*'));
				}
			}
			return aHistory;
		},
		getHistory: function(){
			var aHistory = [];
			for(var i=0; i<this.iMaxHistoryCount/this.iPerCookieSaveCount; i++){
				if(this.getCookie('giant_history_'+i) != ''){
					aHistory = aHistory.concat(this.getCookie('giant_history_'+i).split('*'));
					this.setCookie('giant_history_'+i, '');
				}
			}
			return aHistory;
		},
		setHistory: function(aHistory){
			var num = 0;
			var sCookie = '';
			var code = 0;
			for(var i=0; i<aHistory.length; i++){
				
				if(num<this.iMaxHistoryCount/this.iPerCookieSaveCount){
					if(sCookie != ''){
						sCookie += '*' + aHistory[i];
					}else{
						sCookie += aHistory[i];
					}
					if(i==aHistory.length-1){
						this.setCookie('giant_history_'+code, sCookie);
						break;
					}
					num++;
				}else{
					
					this.setCookie('giant_history_'+code, sCookie);
					num = 0;
					sCookie = '';
					i--;
					code++;
				}
			}
		},
		addHistory: function(cname, curl, cid){
			var aHistory = [];
			aHistory = this.getHistory();
			aHistory.push(cname + '|' + curl + '|' + cid);
			this.setHistory(aHistory);
		},
		updateHistory: function(cname, curl, cid, index){
			var aHistory = [];
			aHistory = this.getHistory();
			aHistory.splice(index, 1, cname + '|' + curl + '|' + cid);
			this.setHistory(aHistory);
		},
		deleteHistory: function(index){
			var aHistory = [];
			aHistory = this.getHistory();
			aHistory = $.grep( aHistory, function(n,i){
			  return index == i;
			}, true);
			this.setHistory(aHistory);
		},
		getExpDate: function(days, hours, minutes){
			var expDate = new Date();
			if(typeof(days) == "number" && typeof(hours) == "number" && typeof(hours) == "number"){
				expDate.setDate(expDate.getDate() + parseInt(days));
				expDate.setHours(expDate.getHours() + parseInt(hours));
				expDate.setMinutes(expDate.getMinutes() + parseInt(minutes));
				return expDate.toGMTString();
			}
		},
		getCookieVal: function(offset){
			var endstr = document.cookie.indexOf(";", offset);
			if(endstr == -1){
				endstr = document.cookie.length;
			}
			return unescape(document.cookie.substring(offset, endstr));
		},
		getCookie: function(name){
			var arg = name + "=";
			var alen = arg.length;
			var clen = document.cookie.length;
			var i = 0;
			while(i < clen){
				var j = i + alen;
				if (document.cookie.substring(i, j) == arg){
					return this.getCookieVal(j);
				}
				i = document.cookie.indexOf(" ", i) + 1;
				if(i == 0) break;
			}
			return "";
		},
		setCookie: function(name, value, expires, path, domain, secure){
			document.cookie = name + "=" + escape(value) +
							((expires) ? "; expires=" + this.getExpDate(1,0,0) : "") +
							((path) ? "; path=" + path : "") +
							((domain) ? "; domain=" + domain : "") +
							((secure) ? "; secure" : "");
		},
		delCookie: function(name,path,domain){
			if(this.getCookie(name) != ''){
				document.cookie = name + "=" +
				((path) ? "; path=" + path : "") +
				((domain) ? "; domain=" + domain : "") +
				"; expires=Thu, 01-Jan-70 00:00:01 GMT";
			}
		},
		isExist: function(tabId){
			var $this = this;
			var i = -1;
			$.each($this.aTabs,function(index, itm){
				if(tabId == itm.tabId){
					i=index;
					return;
				}
			})
			return i;
		},
		addTab: function(options){
			//添加一个选项卡，同时修改cookie，并设置此选项卡为当前选项卡
			var index = this.aTabs.length;
			var $this = this;
			var oTab = {};
			var oElmTab = $('<li class="l"></li>');
			var oElmTabCont = $('<a href="javascript:void(0);" class="ctn"></a>');
			oElmTabCont.attr('href',options.tabUrl);
			oElmTabCont.html(options.tabName);
			var oElmTabClose = $('<a href="javascript:void(0);" class="close"></a>');
			oTab.tab = oElmTab;
			oTab.tabCont = oElmTabCont;
			oTab.tabClose = oElmTabClose;
			oTab.tabUrl = options.tabUrl;
			oTab.tabId = options.tabId;
			this.aTabs.push(oTab);
			
			var oElmListItm = $('<li></li>');
			var oElmListItmCont = $('<a href="javascript:void(0);"></a>');
			var oElmListItmClose = $('<a href="javascript:void(0);" class="close"></a>');
			oTab.listItm = oElmListItm;
			oTab.listItmCont = oElmListItmCont;
			oTab.listItmClose = oElmListItmClose;
			oElmListItmCont.attr('href',oTab.tabCont.attr('href'));
			oElmListItmCont.html(oTab.tabCont.html());
			oTab.listItmCont.bind('mousedown', function(event){
				$this.setCookie('currentIndex',$.inArray(oTab, $this.aTabs));
			})
			oTab.listItmClose.bind('click',function(event){
				var index = $.inArray(oTab, $this.aTabs);
				var cindex = $this.iCurrentIndex;
				$this.removeTab($.inArray(oTab, $this.aTabs));
				if(index == cindex){
					//如果关闭的是当前选项卡
					location.href = $this.aTabs[$this.iCurrentIndex].tabUrl;
				}
			});
			oElmListItm.append(oElmListItmCont);
			oElmListItm.append(oElmListItmClose);
			this.elmDropDownListCtn.append(oElmListItm);
			
			oTab.tabCont.bind('mousedown', function(et){
				$this.setCookie('currentIndex',$.inArray(oTab, $this.aTabs));
			})
			oTab.tabClose.bind('click',function(event){
				var index = $.inArray(oTab, $this.aTabs);
				var cindex = $this.iCurrentIndex;
				$this.removeTab($.inArray(oTab, $this.aTabs));
				if(index == cindex){
					//如果关闭的是当前选项卡
					location.href = $this.aTabs[$this.iCurrentIndex].tabUrl;
				}
			});
			
			oTab.tab.append(oTab.tabCont);
			oTab.tab.append(oTab.tabClose);
			this.elmUserTabCtn.append(oTab.tab);
			
		},
		removeTab: function(index){
			//移除一个选项卡，同时修改cookie，并把前一位置的选项卡设置为当前选项卡
			//判断新添选项卡左边是否被隐藏，若被隐藏，向右移动
			if(parseInt(this.elmUserTabCtn.css('margin-left'))<0){
				this.elmUserTabCtn.css('margin-left',(parseInt(this.elmUserTabCtn.css('margin-left'))+this.iUserTabWidth) + 'px');
			}
			this.aTabs[index].tab.remove();
			this.aTabs[index].listItm.remove();
			if(index == this.iCurrentIndex){
				this.iCurrentIndex--;
				if(this.iCurrentIndex == this.iSystemTabCount-1){
					this.iCurrentIndex = 0;
				}
				this.showTab(this.iCurrentIndex);
			} else{
				if((index < this.iCurrentIndex))
					this.iCurrentIndex--;
					if(this.iCurrentIndex == this.iSystemTabCount-1){
						this.iCurrentIndex = 0;
					}
			}
			
			
			
			$this.setCookie('currentIndex',this.iCurrentIndex);
			this.deleteHistory(index-this.iSystemTabCount);
			this.aTabs = $.grep(this.aTabs,function(n, i){
				return i==index;
			},true);
			if(this.aTabs.length<=$this.iShowUserTabCount + $this.iSystemTabCount){
				this.btnMoveLeft.hide();
				this.btnMoveRight.hide();
				this.btnDropDown.hide();
			}
			if(parseInt(this.elmUserTabCtn.css('margin-left')) == 0){
				$this.btnMoveLeft.addClass('offleft');
				$this.btnMoveRight.removeClass('offright');
			}
			if(parseInt(this.elmUserTabCtn.css('margin-left')) == -($this.aTabs.length - $this.iShowUserTabCount - $this.iSystemTabCount)*$this.iUserTabWidth){
				$this.btnMoveRight.addClass('offright');
				$this.btnMoveLeft.removeClass('offleft');
			}
			
		},
		showTab: function(index){
			this.aTabs[index].tabCont.addClass('current');
			this.aTabs[index].listItmCont.addClass('current');
			if(this.aTabs.length<=this.iShowUserTabCount + this.iSystemTabCount){
				this.btnMoveLeft.hide();
				this.btnMoveRight.hide();
				this.btnDropDown.hide();
			}else{
				this.btnMoveLeft.show();
				this.btnMoveRight.show();
				this.btnDropDown.show();
				if(parseInt(this.elmUserTabCtn.css('margin-left')) == 0){
					this.btnMoveLeft.addClass('offleft');
					this.btnMoveRight.removeClass('offright');
				}
				if(parseInt(this.elmUserTabCtn.css('margin-left')) == -(this.aTabs.length - this.iShowUserTabCount - this.iSystemTabCount)*this.iUserTabWidth){
					this.btnMoveRight.addClass('offright');
					this.btnMoveLeft.removeClass('offleft');
				}
			}
			
			
			//判断选项卡是否被隐藏，若被隐藏在左边，则在最左端出现，若被隐藏在右端，则在最右端出现。
			if(index <= this.iSystemTabCount-1) return;
			this.btnMoveLeft.addClass('offleft');
			this.btnMoveRight.addClass('offright');
			
			if((index-this.iSystemTabCount)*this.iUserTabWidth<-parseInt(this.elmUserTabCtn.css('margin-left'))){
				//被隐藏在左边
				this.elmUserTabCtn.css('margin-left',-(index-this.iSystemTabCount)*this.iUserTabWidth + 'px');
				
			}
			else if((index-(this.iSystemTabCount-1))*this.iUserTabWidth>this.elmUserTabCtn.parent().width()-parseInt(this.elmUserTabCtn.css('margin-left'))){
				//被隐藏在右边
				this.elmUserTabCtn.css('margin-left',(this.elmUserTabCtn.parent().width()-(index-(this.iSystemTabCount-1))*this.iUserTabWidth) + 'px');
				
			}
			if(parseInt(this.elmUserTabCtn.css('margin-left')) == 0){
				$this.btnMoveLeft.addClass('offleft');
				$this.btnMoveRight.removeClass('offright');
			}
			else if(parseInt(this.elmUserTabCtn.css('margin-left')) == -($this.aTabs.length - $this.iShowUserTabCount - $this.iSystemTabCount)*this.iUserTabWidth){
				$this.btnMoveRight.addClass('offright');
				$this.btnMoveLeft.removeClass('offleft');
			} else{
				this.btnMoveLeft.removeClass('offleft');
				this.btnMoveRight.removeClass('offright');
			}
			
			$this.setCookie('marginLeft',this.elmUserTabCtn.css('margin-left'));
		}
	}
})(jQuery);